package com.changgou.order.mq.listener;

import com.alibaba.fastjson.JSON;
import com.changgou.order.service.OrderService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RabbitListener(queues = "${mq.pay.queue.order}")
public class PayMessageListener {

    @Autowired
    private OrderService orderService;

    /**
     * 接收MQ消息监听器
     * @param msg
     */
    @RabbitHandler
    public void receiveMsg(String msg){
        //将消息转换为map
        Map<String,String> map = JSON.parseObject(msg, Map.class);

        //订单id
        String orderId = map.get("out_trade_no");

        if ("SUCCESS".equals(map.get("result_code"))){
            //支付成功，更新订单
            //支付成功后，在微信支付系统存在一个交易号 transaction_id
            orderService.updateStatus(orderId,"1",map.get("transaction_id"));
        }else {
            // 支付失败；也更新订单
            orderService.updateStatus(orderId,"2",null);
        }
    }
}
